package com.genghis.ptas.note.dao.impl;

import com.genghis.core.page.dao.PageDao;
import com.genghis.ptas.note.dao.NoteDao;
import com.genghis.ptas.note.entity.NoteInfo;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

/**
 *
 * @author tiangc
 * @version 1.0.1
 */

@Repository("noteDao")
public class NoteDaoImpl extends PageDao implements NoteDao {
    @Override
    public int addNoteInfo(NoteInfo noteInfo) {
            String sql = "INSERT INTO notes(user_id, content, note_time, scorm_id) VALUES(:userId, :content, :noteTime, :scormId)";
            KeyHolder keyHolder = new GeneratedKeyHolder();
            getNamedParameterJdbcTemplate().update(sql, new BeanPropertySqlParameterSource(noteInfo), keyHolder);
            return keyHolder.getKey().intValue();
    }

    @Override
    public NoteInfo findNoteInfoByScormIdAndUserId(int scormId, int userId) {
        String sql="SELECT * FROM notes n WHERE n.user_id="+userId+" AND n.scorm_id="+scormId;
        return getJdbcTemplate().queryForObject(sql.toString(),new BeanPropertyRowMapper<NoteInfo>(NoteInfo.class));
    }

    @Override
    public int findIsNoteById(int scormId, int userId) {
        String sql="SELECT COUNT(*) FROM notes n WHERE n.user_id="+userId+" AND n.scorm_id="+scormId;
        return getJdbcTemplate().queryForInt(sql.toString());
    }

    @Override
    public void editNote(NoteInfo noteInfo) {
        String sql="UPDATE notes SET user_id=:userId,content=:content,note_time=:noteTime,scorm_id=:scormId WHERE id=:id";
        getNamedParameterJdbcTemplate().update(sql,new BeanPropertySqlParameterSource(noteInfo));
    }
}